$(document).ready(function() {
    reloadTree();
    $('#reset').click();
    layui.use('form', function() {
        var form = layui.form;

        //监听提交
        form.on('submit(formDemo)', function(data) {
           let params = new FormData();

            params.append('euid', data.field.euid);
            params.append('name', data.field.name);
            params.append('type', data.field.type);
            params.append('simId', data.field.simid);
            params.append('linkman', data.field.person);
            params.append('contactnumber', data.field.phone);
            params.append('notifySms', data.field.sms);
            params.append('notifyVms', data.field.vms);
            params.append('rackNum', data.field.racknum);
             params.append('bedChamberName', data.field.bedname);
            params.append('mac', data.field.mac);
             params.append('url', data.field.url);
            addNode(params)
            return false;
        });

        form.on('select(selfilter1)', function(data) {
            if (data.value == 1){
                $('#nracknum').show();
                $('#nbedname').hide();
                $('#nmac').hide();
                $('#nurl').hide();
                $('#racknum').attr('lay-verify', 'required');
                $('#bedname').removeAttr('lay-verify');
                $('#mac').removeAttr('lay-verify');
                $('#url').removeAttr('lay-verify');
            } else if (data.value == 2){
                $('#nracknum').hide();
                $('#nbedname').show();
                $('#nmac').show();
                $('#nurl').hide();
                $('#racknum').removeAttr('lay-verify');
                $('#bedname').attr('lay-verify', 'required');
                $('#mac').attr('lay-verify', 'required');
                $('#url').removeAttr('lay-verify');
            } else if(data.value == 3){
                $('#nracknum').hide();
                $('#nbedname').hide();
                $('#nmac').hide();
                $('#nurl').show();
                $('#racknum').removeAttr('lay-verify');
                $('#bedname').removeAttr('lay-verify');
                $('#mac').removeAttr('lay-verify');
                $('#url').attr('lay-verify', 'required');
            } else {
                $('#nracknum').hide();
                $('#nbedname').hide();
                $('#nmac').hide();
                $('#nurl').hide();
                $('#racknum').removeAttr('lay-verify');
                $('#bedname').removeAttr('lay-verify');
                $('#mac').removeAttr('lay-verify');
                $('#url').removeAttr('lay-verify');
            }
        });
    });

    /*日历插件*/
    layui.use('laydate', function() {
        var laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#date-input',
            range: true,

        });
    });
})

var roomId = '';
var areacode = '';
var isPar = '';
var operate;
let prarms = {};
//机房表格
function loadNodeTable() {
    if (prarms) {
        name = prarms.name;
        type = prarms.type;
        startTime = prarms.startTime;
        endTime = prarms.endTime;
    } else {
        var name = '';
        var type = '';
        var startTime = '';
        var endTime = '';
    }
    layui.use('table', function() {
        var table = layui.table;

        //第一个实例
        table.render({
            title: '',
            text: {
                none: '暂无数据'
            },
            elem: '#body-content-table',
            skin: 'nob',
            url: ajaxPrefix() + '/manage/node/list',
            headers: { SessionId: localStorage.getItem('sessionId') },
            where: {
                pageSize: 10,
                roomId:roomId,
                areaCode:areacode,
                name:name,
                type:type,
                startTime:startTime,
                endTime:endTime
            },
            parseData: function(res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            },
            request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                    ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            page: {
                limit: 10,
            } //开启分页
            ,
            cols: [
                [ //表头
                    {
                        field: 'euid',
                        title: '设备号',
                        align: 'center'
                    }, {
                        field: 'name',
                        title: '设备名称',
                        align: 'center'
                    }, {
                        field: 'type',
                        title: '设备类型',
                        templet: function(d) {
                            var type;
                            if(d.type == 1){
                                type = 'PDU';
                            } else if(d.type == 2){
                                type = '门锁';
                            } else if(d.type == 3){
                                type = '摄像头';
                            } else if(d.type == 4){
                                type = '温湿度';
                            }
                            return type;
                        },
                        align: 'center'
                    }, {
                        field: 'createTime',
                        title: '创建时间',
                        templet: function(d) {
                            return d.createTime == undefined ? '暂无' : d.createTime.substring(0, 19)
                        },
                        align: 'center'
                    }, {
                        field: 'notifySms',
                        title: '短信通知',
                        templet: function(d) {
                            var notifysms;
                            if(d.notifySms == 0){
                                notifysms = '否';
                            } else if(d.notifySms == 1){
                                notifysms = '是';
                            }
                            return notifysms;
                        },
                        align: 'center',
                        width: 90
                    },{
                        field: 'notifyVms',
                        title: '语音通知',
                        templet: function(d) {
                            var notifyvms;
                            if(d.notifyVms == 0){
                                notifyvms = '否';
                            } else if(d.notifyVms == 1){
                                notifyvms = '是';
                            }
                            return notifyvms;
                        },
                        align: 'center',
                        width: 90
                    },{
                        field: 'linkman',
                        title: '联系人',
                        align: 'center'
                    },
                    {
                        field: 'contactnumber',
                        title: '联系电话',
                        align: 'center'
                    },
                    {
                        title: '操作',
                        align: 'center',
                        width: 120,
                        templet: function(d) {
                            let res = JSON.stringify(d);
                            return `<div>
                                        <div class="table-tool">
                                            <div onclick=initUpdate('${d.id}','${d.euid}','${escape(d.name)}','${d.type}','${d.simId}','${d.linkman}','${d.contactnumber}','${d.notifySms}','${d.notifyVms}','${d.rackNum}','${d.bedChamberName}','${d.mac}','${d.url}')><button>修改</button></div>
                                            <div onclick=del('${d.id}')><button>删除</button></div>
                                        </div>
                                   </div>`;

                        },
                    },
                ]
            ]
        });
    });
}

function initUpdate(id,euid,name,type,
    simId,linkman,contactnumber,notifySms,notifyVms,
    rackNum,bedChamberName,mac,url) {
            operate = id;
            $('.add-node>.main-tit>label').html('修改');
            $("#euid").val(euid);
            $("#name").val(unescape(name));
            $("#node-type").val(type);
            renderForm();
            $("#simid").val(simId);
            $("#person").val(linkman);
            $("#phone").val(contactnumber);
            $("#sms").val(notifySms);
            renderForm();
            $("#vms").val(notifyVms);
            renderForm();
            if (type == 1){
                $('#nracknum').show();
                $('#nbedname').hide();
                $('#nmac').hide();
                $('#nurl').hide();
                $("#racknum").val(rackNum);
                $('#racknum').attr('lay-verify', 'required');
                $('#bedname').removeAttr('lay-verify');
                $('#mac').removeAttr('lay-verify');
                $('#url').removeAttr('lay-verify');
            } else if (type == 2){
                $('#nracknum').hide();
                $('#nbedname').show();
                $('#nmac').show();
                $('#nurl').hide();
                $("#bedname").val(bedChamberName);
                $("#mac").val(mac);
                $('#racknum').removeAttr('lay-verify');
                $('#bedname').attr('lay-verify', 'required');
                $('#mac').attr('lay-verify', 'required');
                $('#url').removeAttr('lay-verify');
            } else if(type == 3){
                $('#nracknum').hide();
                $('#nbedname').hide();
                $('#nmac').hide();
                $('#nurl').show();
                $("#url").val(url);
                $('#racknum').removeAttr('lay-verify');
                $('#bedname').removeAttr('lay-verify');
                $('#mac').removeAttr('lay-verify');
                $('#url').attr('lay-verify', 'required');
            } else {
                $('#nracknum').hide();
                $('#nbedname').hide();
                $('#nmac').hide();
                $('#nurl').hide();
                $('#racknum').removeAttr('lay-verify');
                $('#bedname').removeAttr('lay-verify');
                $('#mac').removeAttr('lay-verify');
                $('#url').removeAttr('lay-verify');
            }
            $('.add-node').show();
}

function del(id) {
    var url = '/manage/node/delete?id='+id;
    layer.confirm('确定删除该设备吗?', {
        btn: ['确定', '取消']
    }, function(isConfirm) {
        Ajax(url, delUserCallBack);
        function delUserCallBack(result){
            layer.msg("删除成功");
            loadNodeTable();
        }

    });
}

/*树*/
var setting = {
    async: {
        autoParam: ["id"],
        enable: true,
        url: getAsyncUrl,
        type: "get",
        dataFilter: ajaxDataFilter,
        headers: { "SessionId": localStorage.getItem('sessionId') },
    },
    view: {
        expandSpeed: "fast",
        fontCss: getFont,
        showLine: true,
        dblClickExpand: false,
        showIcon: false
    },
    callback: {
        onAsyncSuccess: zTreeOnAsyncSuccess,
        onClick: zTreeOnClick,
        beforeExpand: beforeExpand,
        onExpand: onExpand
    },
    data: {
        key: {
            title: "name"
        },
        simpleData: {
            enable: true,
            idKey: "code",
            pIdKey: "parentCode"
        }
    }
};

var zNodes;
function reloadTree() {
    zTree = $.fn.zTree.init($("#treeDemo"), setting);
}

function getAsyncUrl(treeId, treeNode) {
    if (!treeNode) {
        url = ajaxPrefix() + "/area/roomtree?areaCode=" + 320113;
    } else {
        url = ajaxPrefix() + "/area/roomtree?areaCode=" + treeNode.id;
    }

    return url;
}

//异步数据过滤
function ajaxDataFilter(treeId, parentNode, childNodes) {

    return childNodes;
}

var _selTreeId = null;
//异步加载成功
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
    if (!treeNode) { //根节点
        var rootNode = zTree.getNodesByParam("level", 0)[0];
        return;
    }

    var selTreeId = _selTreeId;
    if (!!selTreeId) {
        var selNode = zTree.getNodeByParam("id", selTreeId);
        if (!!selNode) {
            _selTreeId = null;
            zTree.selectNode(selNode);
            zTreeOnClick();
        }
    }
}

//获取选中的节点
function getSelectedNode() {
    var treeNode = zTree.getSelectedNodes();
    if (treeNode.length == 0) {

        return false;
    }
    return treeNode[0];
}

//刷新子节点并确定要选中节点ID
var _selTreeId = null;

function reloadNode(refreshId, isParent, selTreeId) {
    var node = zTree.getNodeByParam("id", refreshId);
    if (!!node && !!isParent) {
        node = node.getParentNode();
        if (!node) {
            _selTreeId = selTreeId;
            reloadTree();
            return;
        }
    }
    if (!!node) {
        _selTreeId = selTreeId;
        zTree.reAsyncChildNodes(node, "refresh");
    }
}

//右击事件
function getFont(treeId, node) {
    return node.font ? node.font : {};
}

//仅能打开一个子节点
var curExpandNode = null;

function beforeExpand(treeId, treeNode) {
    var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
    var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
    for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
        if (treeNode !== treeNodeP.children[i]) {
            zTree.expandNode(treeNodeP.children[i], false);
        }
    }
    while (pNode) {
        if (pNode === treeNode) {
            break;
        }
        pNode = pNode.getParentNode();
    }
    if (!pNode) {
        singlePath(treeNode);
    }

}

function singlePath(newNode) {
    if (newNode === curExpandNode) return;
    if (curExpandNode && curExpandNode.open == true) {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        if (newNode.parentTId === curExpandNode.parentTId) {
            zTree.expandNode(curExpandNode, false);
        } else {
            var newParents = [];
            while (newNode) {
                newNode = newNode.getParentNode();
                if (newNode === curExpandNode) {
                    newParents = null;
                    break;
                } else if (newNode) {
                    newParents.push(newNode);
                }
            }
            if (newParents != null) {
                var oldNode = curExpandNode;
                var oldParents = [];
                while (oldNode) {
                    oldNode = oldNode.getParentNode();
                    if (oldNode) {
                        oldParents.push(oldNode);
                    }
                }
                if (newParents.length > 0) {
                    zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
                } else {
                    zTree.expandNode(oldParents[oldParents.length - 1], false);
                }
            }
        }
    }
    curExpandNode = newNode;
}

function onExpand(event, treeId, treeNode) {
    curExpandNode = treeNode;
}

//单击树节点事件
function zTreeOnClick(event, treeId, treeNode) {
    isPar = treeNode.type;
   if (treeNode.type == 'room') {
        roomId = treeNode.code;
        areacode = '';
        loadNodeTable();
    } else if (treeNode.type == 'area'){
        areacode = treeNode.code;
        roomId = '';
        loadNodeTable();
    }

}

$('.layui-btn').click(function() {
    if (isPar != 'room') {
        layer.msg('请先在右侧选择机房')
    } else {
        operate = true;
        $('.add-node>.main-tit>label').html('新增');
        $('.add-node').show();
        $('#nracknum').hide();
        $('#nbedname').hide();
        $('#nmac').hide();
        $('#nurl').hide();
    }

})

$(".add-node>.main-tit>div").click(function() {
    $('.add-node').hide();
    $('#reset').click();
})
/*新增设备*/
addNode = (params) => {
if (operate === true) {
 $.ajax({
            url: ajaxPrefix() + '/manage/node/checkNodeInfo?euid=' + params.get('euid'),
            type: 'get',
            beforeSend: function(XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
            },
            contentType: "application/json",
            success: function(res) {
                if (res.status != 200) {

                    layer.msg('设备已存在！', { icon: 7 })
                } else {
                    params.append('roomId', roomId);
                    $.ajax({
                    url: ajaxPrefix() + '/manage/node/add',
                    type: 'post',
                    data: params,
                    dataType: "json",
                    beforeSend: function(XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
                    },
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if (res.status == 200) {
                            layer.msg('新增成功', { time: 1000 });
                            $(".add-node>.main-tit>div").click();
                            loadNodeTable();
                        } else {
                            layer.msg('操作失败！', { time: 1000 })
                        }

                    }
                    });
                }
            }
        });
   } else {
        params.append('id', operate);
        $.ajax({
        url: ajaxPrefix() + '/manage/node/update',
        type: 'post',
        data: params,
        dataType: "json",
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
        },
        cache: false,
        processData: false,
        contentType: false,
        success: function(res) {
            if (res.status == 200) {
                layer.msg('修改成功', { time: 1000 });
                $(".add-node>.main-tit>div").click();
                loadNodeTable();
            } else {
                layer.msg('操作失败！', { time: 1000 })
            }
        }
    });
   }
}

function renderForm() {
    layui.use('form', function() {
        var form = layui.form; 
        form.render();
    });
}

$('.layui-atn').click(function() {
    prarms.name = $('#devicename').val();
    prarms.type = $('#sel').val();
    let date = $('#date-input').val();
    prarms.startTime = date.substring(0, 10);
    prarms.endTime = date.substring(13, 23);
    loadNodeTable(prarms);
})